package src.data;

import java.util.HashSet;
import java.util.Set;
import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import src.domain.User;

public class UserDAO {

	private HibernateProvider provider;

	private static UserDAO instance = null;

	public static UserDAO getInstance() {
		if (instance == null)
			instance = new UserDAO();
		return instance;
	}

	private UserDAO() {
		this.provider = HibernateProvider.getInstance();

	}
	
	public User getByID(User user){
		Criteria criteria = provider.getSession().createCriteria(User.class).add(Restrictions.like("id", user.getId()));
		return (User) criteria.uniqueResult();	
	}
	
	public User getByUserName(User user){
		Criteria criteria = provider.getSession().createCriteria(User.class).add(Restrictions.like("userName", user.getUserName(),MatchMode.EXACT));
		return (User) criteria.uniqueResult();	
	}

	@SuppressWarnings("unchecked")
	public Set<User> getAll() {

		Criteria criteria = provider.getSession().createCriteria(User.class);
		Set<User> set = new HashSet<User>();
		set.addAll(criteria.list());
		
		return set;

	}

	public void save(User user) {

		
		provider.getSession().save(user);
		
	}

	public void saveOrUpdate(User user) {

		provider.getSession().saveOrUpdate(user);
		
	}

	public void update(User user) {	
		provider.getSession().update(user);		
	}

	public void delete(User user) {
		provider.getSession().delete(user);
	}
	
	@SuppressWarnings("unchecked")
	public Set<User> getUsers(User user) {

		Criteria criteria = provider.getSession().createCriteria(User.class).add(Restrictions.like("name", user.getName(),MatchMode.ANYWHERE));
		Set<User> set = new HashSet<User>();
		set.addAll(criteria.list());
		return set;

	}
}
